package guoanmaker.operator.business.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import guoanmaker.operator.business.model.OperatorActivityApplication;
import guoanmaker.operator.business.model.OperatorActivityEnlist;
import guoanmaker.operator.business.model.OperatorActivityPrice;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.OperatorSecckill;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.ProvideCity;
import guoanmaker.operator.business.model.ProviderProvince;
import guoanmaker.operator.business.modelnobind.ActivityEnlistPriceMove;
import guoanmaker.operator.business.modelnobind.EventDetailMove;
import guoanmaker.operator.business.modelnobind.EventDetailsMove;
import guoanmaker.operator.business.modelnobind.LuckDrawAndCoupons;
import guoanmaker.operator.business.modelnobind.LuckdrawRecordMove;
import guoanmaker.operator.business.modelnobind.SkillAndCommdMove;
import guoanmaker.operator.business.repository.OperatorActivityApplicationRepository;
import guoanmaker.operator.business.repository.OperatorActivityPriceRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.OperatorLuckdrawRecordRepository;
import guoanmaker.operator.business.repository.OperatorSecckillRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideCityRepository;
import guoanmaker.operator.business.repository.ProviderProvinceRepository;

@Repository
public class OperatorEventDetailsDao {

	@PersistenceContext
	EntityManager manager;

	@Autowired
	private OperatorUserRepository operatorUserRepository;
	@Autowired
	private ProviderProvinceRepository providerProvinceRepository;
	@Autowired
	private OperatorEventDetailsRepository operatorEventDetailsRepository;
	@Autowired
	private ProvideCityRepository provideCityRepository;
	@Autowired
	private OperatorLuckdrawRecordRepository operatorLuckdrawRecordRepository;
	@Autowired
	private PersonalUserRepository personalUserRepository;
	@Autowired
	private OperatorProviderOrderDao operatorProviderOrderDao;
	@Autowired
	private OperatorLuckDrawDao operatorLuckDrawDao;
	@Autowired
	private SecckillCommodityDao secckillCommodityDao;
	@Autowired
	private OperatorSecckillRepository operatorSecckillRepository;
	@Autowired
	private OperatorActivityPriceRepository activityPriceRepository;
	@Autowired
	private OperatorActivityApplicationRepository applicationRepository;

	public Integer getEventJoinPersonNums(String id, String ActivityTypeId) {
		if (!ActivityTypeId.equals("抽奖")) {
			String jpql = "SELECT sum(e.buyNum) FROM OperatorActivityEnlist e WHERE  e.activityId =:id AND e.state = 1";
			Query createQuery = manager.createQuery(jpql);
			createQuery.setParameter("id", id);
			Long singleResult = (Long) createQuery.getSingleResult();
			manager.clear();
			if (singleResult == null) {
				return 0;
			} else {
				return singleResult.intValue();
			}
		} else {
			Integer item = 0;
			item = operatorLuckdrawRecordRepository.selectByActivityId(id);
			if (item == null) {
				item = 0;
			}
			return item;
		}
	}

	// 通过活动类型id查询活动详情
	public Map<String, Object> getEventById(String id, Integer page, Integer size) {
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,"
				+ "s.event_end_time,s.registration_channel,s.event_join_person_num,s.enrollment,s.weight,s.is_money,s.organizer,s.id,"
				+ "s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,"
				+ "s.event_detailed_address,s.registration_form_details,s.agree_or_not,c. NAME AS place_name,d. NAME AS city_name "
				+ " FROM t_operator_event_details s " + " LEFT JOIN t_provide_province c  ON s.event_place = c.id "
				+ " LEFT JOIN t_provide_city d ON s.event_county = d.id "
				+ "WHERE s.event_type = 1 and s.activity_type_id=:id AND s.state <> 4 AND s.state <> 0 AND s.state <> 7  ORDER BY  s.state=3 asc,s.event_start_time DESC,s.release_time DESC";
		Query createQuery = manager.createNativeQuery(sql, OperatorEventDetailss.class);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;
		createQuery = createQuery.setParameter("id", id);
		if (createQuery.getResultList().size() != 0) {
			map.put("size", createQuery.getResultList().size());
		}
		@SuppressWarnings("unchecked")
		List<OperatorEventDetailss> enlistlist = createQuery.setMaxResults(size).setFirstResult(index).getResultList();
		map.put("cuont", enlistlist);
		manager.clear();// 分离内存中受EntityManager管理的实体bean，让VM进行垃圾回收
		return map;
	}

	// 通过id查询活动详情
	public EventDetailMove getSelectEvent(String id) {
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_pic_app_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,s.event_end_time,s.registration_channel,s.event_join_person_num,"
				+ "s.enrollment,null as price_stock_num,s.weight,s.is_money,s.organizer,s.id,s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,s.event_detailed_address,s.registration_form_details,s.agree_or_not,c.NAME AS place_name,d. NAME AS city_name,"
				+ "ou.`name` as user_name,s.share_infor,s.buid_time  FROM t_operator_event_details s LEFT JOIN t_provide_province c ON s.event_place = c.id LEFT JOIN t_provide_city d ON s.event_county = d.id,t_operator_user ou WHERE s.founder = ou.id and s.id=:id";
		Query query = manager.createNativeQuery(sql, EventDetailMove.class);
		query = query.setParameter("id", id);
		EventDetailMove eventDetails = (EventDetailMove) query.getSingleResult();
		if (eventDetails.getActivityTypeId().equals("抽奖") == true) {
			List<LuckDrawAndCoupons> luckdrawList = operatorLuckDrawDao.queryAllLuckdrawByActivityId(id);
			eventDetails.setLuckdrawList(luckdrawList);
		}
		if (eventDetails.getActivityTypeId().equals("秒杀") == true) {
			List<SkillAndCommdMove> secckillList = secckillCommodityDao.selectSkillAndCommdMoveByActivityId(id);
			eventDetails.setSecckillList(secckillList);
		}
		if (eventDetails.getIsMoney() == 1) {// 收费 1
			List<OperatorActivityPrice> activityPriceList = activityPriceRepository.selectOperatorActivityPrice(id);
			eventDetails.setActivityPriceList(activityPriceList);
		}
		if (eventDetails.getAgreeOrNot() == 1) {// 有报名 表单1
			List<OperatorActivityApplication> applicationList = applicationRepository.queryActivityApplicationList(id);
			eventDetails.setApplicationList(applicationList);
		}
		return eventDetails;
	}

	// 查询线上下线所有活动
	@SuppressWarnings({ "unchecked", "unused" })
	public Map<String, Object> getAllOperatorEventDetails(Integer eventType, Integer page, Integer size) {
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_pic_app_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,s.event_end_time,s.registration_channel,s.event_join_person_num,"
				+ "s.enrollment, (SELECT SUM(ap.stock_num) FROM t_operator_activity_price ap WHERE ap.activity_id=	s.id ) as price_stock_num, s.weight,s.is_money,s.organizer,s.id,s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,s.event_detailed_address,s.registration_form_details,s.agree_or_not,c.NAME AS place_name,d. NAME AS city_name,"
				+ "ou.`name` as user_name,s.share_infor,null as buid_time  FROM t_operator_event_details s LEFT JOIN t_provide_province c ON s.event_place = c.id LEFT JOIN t_provide_city d ON s.event_county = d.id,t_operator_user ou WHERE s.founder = ou.id and s.event_type =:eventType AND s.state <> 4  ORDER BY s.buid_time DESC";
		Query query = manager.createNativeQuery(sql, EventDetailMove.class);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;// 计算开始的记录数
		query = query.setParameter("eventType", eventType);
		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
		}
		Date date = new Date();
		List<EventDetailMove> operatorEventDetails = query.setMaxResults(size).setFirstResult(index).getResultList();
		Long nowTime = new Date().getTime();// 获取当前时间
		for (EventDetailMove eventDetails : operatorEventDetails) {
			if (eventDetails.getAvailability() == 1) {
				Integer orgstate = eventDetails.getState();
				// 0未发布 默认 状态 7是未生效 4 是已删除
				// 报名未开始 6 报名时间 不为空
				if (eventDetails.getSignupStartTime() != null && eventDetails.getSignupStartTime().getTime() > nowTime
						&& eventDetails.getReleaseTime().getTime() <= nowTime && orgstate != 6 && orgstate != 3) {
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 6);
					eventDetails.setState(6);
				}
				// 报名中 5 报名时间 不为空
				else if (eventDetails.getSignupStartTime() != null
						&& eventDetails.getSignupStartTime().getTime() <= nowTime
						&& eventDetails.getSignupEndTime().getTime() > nowTime && orgstate != 5 && orgstate != 3) {
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 5);
					eventDetails.setState(5);
				}
				// 未开始 1 活动开始时间 不能为空
				else if (eventDetails.getEventStartTime() != null && eventDetails.getSignupStartTime() != null
						&& eventDetails.getEventStartTime().getTime() > nowTime
						&& eventDetails.getSignupEndTime().getTime() <= nowTime && orgstate != 1 && orgstate != 3) {
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 1);
					eventDetails.setState(1);
				}
				// 未开始 1 活动开始时间 不能为空

				else if (eventDetails.getEventStartTime() != null && eventDetails.getSignupStartTime() == null
						&& eventDetails.getEventStartTime().getTime() > nowTime
						&& eventDetails.getReleaseTime().getTime() <= nowTime && orgstate != 1 && orgstate != 3) {

					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 1);
					eventDetails.setState(1);
				}
				// 活动开始 2 活动开始时间 不能为空

				else if (eventDetails.getEventStartTime() != null
						&& eventDetails.getEventStartTime().getTime() <= nowTime
						&& eventDetails.getEventEndTime().getTime() > nowTime && orgstate != 2 && orgstate != 3) {

					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 2);
					eventDetails.setState(2);
				}
				// 活动结束 3 活动结束 时间 不能为空
				else if (eventDetails.getEventEndTime() != null && eventDetails.getEventEndTime().getTime() < nowTime
						&& orgstate != 3) {
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 3);
					eventDetails.setState(3);
				}
			}
			if (eventDetails.getActivityTypeId().equals("秒杀") == true) {
				Integer num = operatorProviderOrderDao.querycountnum(eventDetails.getId());
				if (num == null) {
					num = 0;
				}
				eventDetails.setActivePayment(num);
			} else {
				eventDetails.setActivePayment(
						this.getEventJoinPersonNums(eventDetails.getId(), eventDetails.getActivityTypeId()));
				eventDetails.setRecordCount(operatorLuckdrawRecordRepository.queryRecordCount(eventDetails.getId()));
			}
			if (operatorEventDetails != null) {
				map.put("cuont", operatorEventDetails);
			}
		}
		manager.clear();// 分离内存中受EntityManager管理的实体bean，让VM进行垃圾回收
		return map;
	}

	public Map<String, Object> getAppAndIosAndPc(Integer eventType, Integer page, Integer size) {
		if (page == 0 || page == null) {
			return null;
		}
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,"
				+ "s.event_end_time,s.registration_channel,s.event_join_person_num,s.enrollment,s.weight,s.is_money,s.organizer,s.id,"
				+ "s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,"
				+ "s.event_detailed_address,s.registration_form_details,s.agree_or_not,c. NAME AS place_name,d. NAME AS city_name "
				+ " FROM t_operator_event_details s " + " LEFT JOIN t_provide_province c  ON s.event_place = c.id "
				+ " LEFT JOIN t_provide_city d ON s.event_county = d.id "
				+ "WHERE s.event_type = :eventType AND s.state <> 4 AND s.state <> 0 AND s.state <> 7  ORDER BY  s.state=3 asc,s.event_start_time DESC,s.release_time DESC";
		Query query = manager.createNativeQuery(sql, OperatorEventDetailss.class);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;
		query = query.setParameter("eventType", eventType);
		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
		}
		@SuppressWarnings("unchecked")
		List<OperatorEventDetailss> operatorEventDetails = query.setMaxResults(size).setFirstResult(index)
				.getResultList();
		Long nowTime = new Date().getTime();// 获取当前时间
		for (OperatorEventDetailss eventDetails : operatorEventDetails) {
			Integer orgstate = eventDetails.getState();
			// 0未发布 默认 状态 7是未生效 4 是已删除
			// 报名未开始 6 报名时间 不为空
			if (eventDetails.getSignupStartTime() != null && eventDetails.getSignupStartTime().getTime() > nowTime
					&& eventDetails.getReleaseTime().getTime() <= nowTime && orgstate != 6 && orgstate != 3) {
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 6);
				eventDetails.setState(6);
			}
			// 报名中 5 报名时间 不为空
			else if (eventDetails.getSignupStartTime() != null && eventDetails.getSignupStartTime().getTime() <= nowTime
					&& eventDetails.getSignupEndTime().getTime() > nowTime && orgstate != 5 && orgstate != 3) {
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 5);
				eventDetails.setState(5);
			}
			// 未开始 1 活动开始时间 不能为空

			else if (eventDetails.getEventStartTime() != null && eventDetails.getSignupStartTime() != null
					&& eventDetails.getEventStartTime().getTime() > nowTime
					&& eventDetails.getSignupEndTime().getTime() <= nowTime && orgstate != 1 && orgstate != 3) {

				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 1);
				eventDetails.setState(1);
			}
			// 未开始 1 活动开始时间 不能为空
			else if (eventDetails.getEventStartTime() != null && eventDetails.getSignupStartTime() == null
					&& eventDetails.getEventStartTime().getTime() > nowTime
					&& eventDetails.getReleaseTime().getTime() <= nowTime && orgstate != 1 && orgstate != 3) {
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 1);
				eventDetails.setState(1);
			}
			// 活动开始 2 活动开始时间 不能为空

			else if (eventDetails.getEventStartTime() != null && eventDetails.getEventStartTime().getTime() <= nowTime
					&& eventDetails.getEventEndTime().getTime() > nowTime && orgstate != 2 && orgstate != 3) {

				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 2);
				eventDetails.setState(2);
			}
			// 活动结束 3 活动结束 时间 不能为空
			else if (eventDetails.getEventEndTime() != null && eventDetails.getEventEndTime().getTime() < nowTime
					&& orgstate != 3) {
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(), 3);
				eventDetails.setState(3);
			}
		}
		if (operatorEventDetails != null) {
			map.put("cuont", operatorEventDetails);
		}
		manager.clear();// 分离内存中受EntityManager管理的实体bean，让VM进行垃圾回收
		return map;
	}

	// 根据活动标题查询
	@SuppressWarnings({ "unchecked", "unused" })
	public Map<String, Object> LikeSelect(String eventTitle, Integer eventType, Integer page, Integer size) {
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_pic_app_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,s.event_end_time,s.registration_channel,s.event_join_person_num,"
				+ "s.enrollment, (SELECT SUM(ap.stock_num) FROM t_operator_activity_price ap WHERE ap.activity_id=	s.id ) as price_stock_num, s.weight,s.is_money,s.organizer,s.id,s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,s.event_detailed_address,s.registration_form_details,s.agree_or_not,c.NAME AS place_name,d. NAME AS city_name,"
				+ "ou.`name` as user_name,s.share_infor,null as buid_time FROM t_operator_event_details s LEFT JOIN t_provide_province c ON s.event_place = c.id LEFT JOIN t_provide_city d ON s.event_county = d.id,t_operator_user ou  where 1 = 1 and s.founder = ou.id and  s.event_type =:eventType and s.event_title like CONCAT('%',:eventTitle,'%') and s.state <>  4  order by  s.buid_time DESC  ";
		Query query = manager.createNativeQuery(sql, EventDetailMove.class);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;// 计算开始的记录数
		query = query.setParameter("eventType", eventType).setParameter("eventTitle", eventTitle);
		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
			List<EventDetailMove> enlistlist = query.setMaxResults(size).setFirstResult(index).getResultList();
			map.put("cuont", enlistlist);

			for (EventDetailMove operatorEventDetails : enlistlist) {
				if (operatorEventDetails.getActivityTypeId().equals("秒杀") == true) {
					Integer num = operatorProviderOrderDao.querycountnum(operatorEventDetails.getId());
					if (num == null) {
						num = 0;
					}
					operatorEventDetails.setActivePayment(num);
				} else {
					operatorEventDetails.setActivePayment(this.getEventJoinPersonNums(operatorEventDetails.getId(),
							operatorEventDetails.getActivityTypeId()));
					operatorEventDetails.setRecordCount(operatorLuckdrawRecordRepository.queryRecordCount(operatorEventDetails.getId()));
				}
			}
		} else if (query.getResultList().size() == 0) {
			map.put("size", 0);
			map.put("cuont", null);
		}
		manager.clear();
		return map;
	}

	// 多条件查询
	@SuppressWarnings("unchecked")
	public Map<String, Object> multipleConditionQuery(Integer eventType, String eventTitle, Integer state,
			String founder, Integer isMoney, String stratTime, String endTime, Integer page, Integer size) {
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_pic_app_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,s.event_end_time,s.registration_channel,s.event_join_person_num,"
				+ "s.enrollment, (SELECT SUM(ap.stock_num) FROM t_operator_activity_price ap WHERE ap.activity_id=	s.id ) as price_stock_num, s.weight,s.is_money,s.organizer,s.id,s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,s.event_detailed_address,s.registration_form_details,s.agree_or_not,c.NAME AS place_name,d. NAME AS city_name,"
				+ "ou.`name` as user_name,s.share_infor,null as buid_time  FROM t_operator_event_details s LEFT JOIN t_provide_province c ON s.event_place = c.id LEFT JOIN t_provide_city d ON s.event_county = d.id,t_operator_user ou  where 1 = 1 and s.founder = ou.id  and s.state <> 4  ";
		if (eventType != null && !eventType.equals("")) {
			sql += " and s.event_type='" + eventType + "' ";
		}
		if (eventTitle != null && !eventTitle.equals("")) {
			sql += " and s.event_title like'%" + eventTitle + "%' ";
		}
		if (state != null && !state.equals("")) {
			sql += " and s.state='" + state + "' ";
		}
		if (founder != null && !founder.equals("")) {
			sql += " and ou.`name` like'%" + founder + "%' ";
		}
		if (isMoney != null) {
			sql += " and s.is_money='" + isMoney + "' ";
		}
		if (stratTime != null && endTime != null) {
			sql += " and s.event_start_time >='" + stratTime + "' and s.event_end_time <='" + endTime + "'";
		}
		if (stratTime != null && endTime == null) {
			sql += " and s.event_start_time>='" + stratTime + "'";
		}
		if (stratTime == null && endTime != null) {
			sql += " and s.event_end_time<='" + endTime + "'";
		}
		if (true) {
			sql += " order by  s.buid_time DESC";
		}
		if (page == null) {
			page = 1;
		}
		if (size == null) {
			size = 5;
		}

		int index = (page - 1) * size;
		Query query = manager.createNativeQuery(sql, EventDetailMove.class);
		Map<String, Object> map = new HashMap<>();

		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
		}
		List<EventDetailMove> resultList = query.setMaxResults(size).setFirstResult(index).getResultList();
		map.put("cuont", resultList);
		manager.clear();
		return map;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getEventUser(String id, String activityTypeId, Integer page, Integer size) {
		Map<String, Object> map = new HashMap<>();
		if (!activityTypeId.equals("抽奖")) {
			String sql = "SELECT oae.id,oae.activity_id,oae.activity_price_id,oae.buy_num,oae.build_time,oae.infor_value,oae.link_man,oae.tele_phone,oae.company_name,oae.pay_money,oae.sign_channel,oae.state,oae.stream_num,pu.username AS user_name,oap.titel"
					+ " FROM t_operator_activity_enlist oae LEFT JOIN t_operator_activity_price oap on oae.activity_price_id = oap.id , t_personal_user pu WHERE   oae.user_id = pu.id and oae.activity_id=:id and oae.state =1";
			Query query = manager.createNativeQuery(sql, ActivityEnlistPriceMove.class);
			int index = (page - 1) * size;
			query = query.setParameter("id", id);
			if (query.getResultList().size() != 0) {
				map.put("size", query.getResultList().size());
				List<ActivityEnlistPriceMove> enlistlist = query.setMaxResults(size).setFirstResult(index)
						.getResultList();
				map.put("cuont", enlistlist);
			}
			if (query.getResultList().size() == 0) {
				map.put("size", 0);
				map.put("cuont", null);
			}

		} else {
			String sql = "SELECT a.id,a.luckdraw_type,a.record_time,tpa.telephone AS user_tel_adress,tpa.`name` AS user_name_adress,tpa.address, tpu.username as user_tel,tpu.`name` as user_name FROM t_operator_luckdraw_record a LEFT JOIN t_personal_address tpa ON tpa.user_id = a.user_id AND tpa.isdefault = 1 LEFT JOIN   t_personal_user tpu on a.user_id = tpu.id WHERE a.activity_id =:id ORDER BY a.record_time DESC";
			Query query = manager.createNativeQuery(sql, LuckdrawRecordMove.class);
			int index = (page - 1) * size;
			query = query.setParameter("id", id);
			if (query.getResultList().size() != 0) {
				map.put("size", query.getResultList().size());
				List<LuckdrawRecordMove> enlist = (List<LuckdrawRecordMove>) query.setMaxResults(size)
						.setFirstResult(index).getResultList();
				map.put("cuont", enlist);
			}
			if (query.getResultList().size() == 0) {
				map.put("size", 0);
				map.put("cuont", null);
			}
		}
		manager.clear();
		return map;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getEventDetailsOfApplicants(String id, String activityTypeId,String maxTime,String minTime) {
		Map<String, Object> map = new HashMap<>();
		if (!activityTypeId.equals("抽奖")) {
			String sql = "SELECT oae.id,oae.activity_id,oae.activity_price_id,oae.buy_num,oae.build_time,oae.infor_value,oae.link_man,oae.tele_phone,oae.company_name,oae.pay_money,oae.sign_channel,oae.state,oae.stream_num,pu.username AS user_name,oap.titel"
					+ " FROM t_operator_activity_enlist oae LEFT JOIN t_operator_activity_price oap on oae.activity_price_id = oap.id , t_personal_user pu WHERE   oae.user_id = pu.id and oae.activity_id=:id and oae.state =1";
			Query query = manager.createNativeQuery(sql, ActivityEnlistPriceMove.class);
			query = query.setParameter("id", id);
			if (query.getResultList().size() != 0) {
				List<ActivityEnlistPriceMove> enlistlist = query.getResultList();
				map.put("size", query.getResultList().size());
				map.put("cuont", enlistlist);
			}
			if (query.getResultList().size() == 0) {
				map.put("size", 0);
				map.put("cuont", null);
			}

		} else {
			String sql = "SELECT a.id,a.luckdraw_type,a.record_time,tpa.telephone AS user_tel_adress,tpa.`name` AS user_name_adress,tpa.address, tpu.username as user_tel,tpu.`name` as user_name FROM t_operator_luckdraw_record a LEFT JOIN t_personal_address tpa ON tpa.user_id = a.user_id AND tpa.isdefault = 1 LEFT JOIN   t_personal_user tpu on a.user_id = tpu.id WHERE a.activity_id =:id " ;
					if ( maxTime != null && !maxTime.equals("")) {
						sql += " and  a.record_time <='" + maxTime + "' ";
					}
					if ( minTime!= null && !minTime.equals("")) {
						sql += " and  a.record_time >='" + minTime + "' ";
					}
					if (true) {
						sql += " ORDER BY a.record_time DESC ";
					}
			Query query = manager.createNativeQuery(sql, LuckdrawRecordMove.class);
			query = query.setParameter("id", id);
			if (query.getResultList().size() != 0) {
				List<LuckdrawRecordMove> enlist = (List<LuckdrawRecordMove>) query.getResultList();
				map.put("cuont", enlist);
			}

		}
		manager.clear();
		return map;
	}

	public Boolean theQueryActivityTitleIsRepeated(String eventTitle) {
		String jpql = "select s from OperatorEventDetails s where s.eventTitle = :eventTitle and s.state <> 4";
		Query query = manager.createQuery(jpql);
		query = query.setParameter("eventTitle", eventTitle);
		int size = query.getResultList().size();
		if (size == 0) {
			return true;// 没有查询到
		} else {
			return false;// 查询到了
		}
	}

	@SuppressWarnings("unchecked")
	public List<EventDetailsMove> selectSecckillEventDetails() {
		List<EventDetailsMove> list = new ArrayList<>();
		List<EventDetailsMove> listMore = new ArrayList<>();
		/**
		 * 查询 当天 是否 有秒杀活动 ，秒杀活动是否 为 单场 ， - 如果是单场 次 则将  单场全部查出 ， -多场终止
		 */
		String sql = "SELECT oed.id,oed.event_start_time,oed.event_end_time FROM t_operator_event_details oed WHERE oed.activity_type_id = '秒杀'  AND oed.state != 4 AND oed.availability = 1 AND (CAST(oed.event_start_time AS date) >= CAST(NOW() AS date) or oed.event_end_time > NOW() ) ORDER BY oed.event_start_time ASC LIMIT 0,7";
		Query query = manager.createNativeQuery(sql, EventDetailsMove.class);
		if (query.getResultList().size() != 0) {
			List<EventDetailsMove> enlist = (List<EventDetailsMove>) query.getResultList();
			for (EventDetailsMove move : enlist) {
				List<OperatorSecckill> secckillList =operatorSecckillRepository.querySecckillByActivityId(move.getId());
				//遇到 多场次  并且 前面 没有单场次 秒杀 则 返回 单条 多场次 秒杀活动id
				if (secckillList.size() > 1 ) {
					listMore.add(move);
					if(list.size()==0) {
						return listMore;
					}
				} 
				//单场次 秒杀 
				else if (secckillList.size() == 1) {
					move.setType("0");//单场次
					list.add(move);
				}
			}
			return list;
		}
		if (query.getResultList().size() == 0) {
			// 查询以前
			if (query.getResultList().size() == 0) {
				sql = "SELECT oed.id,oed.event_start_time,oed.event_end_time FROM t_operator_event_details oed WHERE oed.activity_type_id = '秒杀'  AND oed.state!=4 AND oed.availability = 1 and oed.event_start_time <=NOW() ORDER BY oed.event_start_time desc LIMIT 0,1";
				query = manager.createNativeQuery(sql, EventDetailsMove.class);
				EventDetailsMove enlist = (EventDetailsMove) query.getSingleResult();
				if (query.getResultList().size() != 0) {
					list.add(enlist);
				}
			}
			return list;
		}
		return null;
	}
	
	/**
	 * 查询 验证 秒杀活动 同一天是否存在
	 */
	public String selectActivityByTime(String dateTime) {
		String sql = "SELECT oed.id,oed.event_start_time,oed.event_end_time FROM t_operator_event_details oed where  cast(oed.event_start_time as date)=:dateTime and oed.activity_type_id='秒杀' and oed.state !=4 ";
		Query query = manager.createNativeQuery(sql, EventDetailsMove.class);
		query = query.setParameter("dateTime", dateTime);
		if (query.getResultList().size() != 0) {
	    List<EventDetailsMove> enlist = query.getResultList();
		return enlist.get(0).getId();
		}
		return null;
	}
	
}
